import React, { useState, useEffect, useRef } from 'react';
import { Button, Form, Input, InputNumber, Card, Switch, Select, Upload, Image, message } from 'antd';
import { UploadOutlined } from '@ant-design/icons'
import { fetchCateLists } from '@a/cateLists'
import { fetchItemDetail, updateItem } from '@a/itemLists'
import { useNavigate, useParams } from 'react-router-dom'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-react'
const ItemUpdate = () => {
  const navigate = useNavigate();
  // 获取修改商品详情数据
  const form = useRef();
  const routeParams = useParams();
  // 动态设置表单初始值
  const getItemDetail = () => {
    fetchItemDetail(routeParams).then(res => {
      if(res.data.code === 200) {
        form.current.setFieldsValue(res.data.data)
        // 设置封面的初始值
        setThumb(res.data.data.thumb)
        // 设置富文本初始值
        setHtml(res.data.data.content)
      }
    })
  }
  // 图片上传状态改变事件
  const [thumb, setThumb] = useState('');
  const uploadStatusChange = (info) => {
    if (info.file.status === 'done') {
      setThumb(info.file.response.data.url)
    }
  }
  // 提交表单新增商品
  const onsubmitItemForm = (params) => {
    params.thumb = thumb;
    params.content = html; // 富文本编辑器内容
    updateItem(params).then(res => {
      if (res.data.code === 200) {
        message.success(res.data.msg, 2, () => {
          // 去商品列表页
          navigate('/itemLists', {replace: true})
        })
      }
    })
  };

  // 富文本编辑器
  const [editor, setEditor] = useState(null);
  const [html, setHtml] = useState('');
  const toolbarConfig = {}
  const editorConfig = {                         // JS 语法
    placeholder: '请输入内容...',
    MENU_CONF: {
      uploadImage: {
        server: '/api/upload',
        fieldName: 'file',
        customInsert: (res, insertFn) => {
          
          insertFn(res.data.url)
        }
      }
    }
  }
  // 富文本编辑器

  // 所有商品分类 新增商品分类
  const [cates, setCates] = useState([]);
  const getCates = () => {
    fetchCateLists().then(res => {
      if (res.data.code === 200) {
        const _cates = res.data.data.lists;
        setCates([
          ..._cates.map(cate => {
            return {
              label: cate.cateName,
              value: cate.id
            }
          })
        ])
      }
    })
  }

  useEffect(() => {
    getCates();
    getItemDetail();
  }, [])
  return (
    <Card title="修改商品" style={{ maxWidth: 900 }}>
      <Form
        name="basic"
        ref={form}
        labelCol={{
          span: 4,
        }}
        wrapperCol={{
          span: 20,
        }}
        initialValues={{
          cateId: '请选择分类'
        }}
        onFinish={onsubmitItemForm}
        autoComplete="off"
      >
        <Form.Item
          label="商品名"
          name="itemName"
          rules={[
            {
              required: true,
              message: '商品名必须输入!',
            },
          ]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label="商品价格"
          name="price"
          rules={[
            {
              required: true,
              message: '商品价格必须输入!',
            },
          ]}
        >
          <InputNumber min={0} />
        </Form.Item>
        <Form.Item
          label="上下架"
          name="onsale"
          valuePropName='checked'
        >
          <Switch defaultChecked />
        </Form.Item>
        <Form.Item
          label="商品分类"
          name="cateId"
          rules={[
            {
              required: true,
              message: '商品分类必填!',
            },
          ]}
        >
          <Select
            style={{
              width: 120,
            }}

            options={cates}
          />
        </Form.Item>
        <Form.Item
          label="描述"
          name="desc"

        >
          <Input.TextArea />
        </Form.Item>
        <Form.Item
          label="商品封面"

        >
          <Upload
            accept='image/*'
            action="/api/upload"
            onChange={uploadStatusChange}
          >
            <Button icon={<UploadOutlined />}>点击上传</Button>
          </Upload>
          <Image src={thumb} width={80}></Image>
        </Form.Item>
        <Form.Item
          label="商品内容"

        >
          {/* 富文本编辑器 */}
          <div style={{border: '1px solid #999'}}>
            <Toolbar
              editor={editor}
              defaultConfig={toolbarConfig}
              mode="default"
              style={{ borderBottom: '1px solid #ccc' }}
            />
            <Editor
              defaultConfig={editorConfig}
              value={html}
              onCreated={setEditor}
              onChange={editor => setHtml(editor.getHtml())}
              mode="default"
              style={{ height: '500px', overflowY: 'hidden' }}
            />
          </div>
          {/* /富文本编辑器 */}
        </Form.Item>
        <Form.Item
          wrapperCol={{
            offset: 8,
            span: 16,
          }}
        >
          <Button type="primary" htmlType="submit">
            确定
          </Button>
        </Form.Item>
      </Form>
    </Card>
  );
};
export default ItemUpdate;